package com.gzc.just.play.last.war.gateserver.handler;

import com.gzc.just.play.last.war.common.annotation.MessageHandler;
import com.gzc.just.play.last.war.common.connection.ServerConnectionManager;
import com.gzc.just.play.last.war.common.handler.SimpleMessageHandler;
import com.gzc.just.play.last.war.common.net.NetUtils;
import com.gzc.just.play.last.war.gateserver.connection.GateServerConnector;
import com.gzc.just.play.last.war.protobuf.gc.gctocs.GCToCS;
import com.gzc.just.play.last.war.protobuf.gs.gstocs.GSToCS;
import com.gzc.just.play.last.war.protobuf.gs.gstogc.GSToGC;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 简化的登录消息处理器
 * 处理来自Unity客户端的登录请求
 */
@Component
@MessageHandler(serverTypes = {MessageHandler.ServerType.GATE_SERVER})
public class SimpleLoginHandler implements SimpleMessageHandler {
    private static final Logger logger = LoggerFactory.getLogger(SimpleLoginHandler.class);
    
    // 登录请求的消息ID
    private static final int LOGIN_MESSAGE_ID = 8193; // eMsgToGSToCSFromGC_AskLogin
    
    // 登录响应的消息ID
    private static final int LOGIN_RESPONSE_ID = 5; // eMsgToGCFromGS_GCAskRet

    @Autowired
    private GateServerConnector gateServerConnector;
    
    @Override
    public void handle(Object message, ChannelHandlerContext ctx) throws Exception {
        handleMessage(message, ctx);
    }
    
    public void handleMessage(Object message, ChannelHandlerContext ctx) throws Exception {
        if (!(message instanceof GCToCS.Login)) {
            logger.error("Expected Login message but got: {}", 
                        message != null ? message.getClass().getName() : "null");
            return;
        }
        
        GCToCS.Login loginRequest = (GCToCS.Login) message;
        
        logger.info("Handling login request from: {}", ctx.channel().remoteAddress());
        logger.info("Login request: name={}, equimentid={}", 
                   loginRequest.getName(), loginRequest.getEquimentid());
        
        try {
            // Get Session ID (NSID)
            Long sessionId = ctx.channel().attr(com.gzc.just.play.last.war.common.handler.VirtualThreadNettyServer.ServerAttributes.SESSION_ID).get();
            if (sessionId == null) {
                logger.error("Session ID not found for connection {}", ctx.channel().remoteAddress());
                return;
            }

            // Forward to Central Server
            GSToCS.ReportGCMsg reportMsg = GSToCS.ReportGCMsg.newBuilder()
                .setMsgid(GSToCS.MsgID.eMsgToCSFromGS_ReportGCMsg)
                .setNsid(sessionId.intValue())
                .setOthermsgid(LOGIN_MESSAGE_ID)
                .setOthermsg(loginRequest.toByteString())
                .build();

            gateServerConnector.getConnectionManager().sendMsg(
                ServerConnectionManager.ServerType.CENTRAL_SERVER, 
                8195, // eMsgToCSFromGS_ReportGCMsg
                reportMsg
            );
            
            logger.info("Forwarded Login request to Central Server for NSID: {}", sessionId);

        } catch (Exception e) {
            logger.error("Error handling login", e);
            GSToGC.AskRet response = createLoginResponse(LOGIN_MESSAGE_ID, 1);
            NetUtils.sendMsg(ctx.channel(), LOGIN_RESPONSE_ID, response);
        }
    }
    
    /**
     * 创建登录响应消息
     * @param askId 请求的消息ID
     * @param errorCode 错误码（0表示成功，非0表示错误）
     * @return 响应消息对象
     */
    private GSToGC.AskRet createLoginResponse(int askId, int errorCode) {
        return GSToGC.AskRet.newBuilder()
                .setAskid(askId)
                .setErrorcode(errorCode)
                .build();
    }
    
    @Override
    public int getMessageId() {
        return LOGIN_MESSAGE_ID;
    }
    
    @Override
    public String getName() {
        return "SimpleLoginHandler";
    }
    
    @Override
    public Logger getLogger() {
        return logger;
    }
}